package com.cloud.api.annotation;

import cn.hutool.core.util.ObjectUtil;
import com.alicp.jetcache.Cache;
import com.cloud.api.domain.SysUserDept;
import com.cloud.core.entity.base.BaseEntity;
import com.cloud.core.exception.MyException;
import com.cloud.mybatis.domain.TableDataInfo;
import jakarta.annotation.Resource;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

@Aspect
@Component
@Lazy(false)
public class TransAction {
    private static final Logger log = LoggerFactory.getLogger(TransAction.class);

    @Resource(name = "myRedis")
    private RedisTemplate<String, Object> redisTemplate;
    @Resource
    private Cache<String, SysUserDept> userCache;
    
    
    @Around("@annotation(com.cloud.api.annotation.TransUser)")
    public Object interceptor(ProceedingJoinPoint joinPoint) {
        Object proceed = null;
        try{
            proceed = joinPoint.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            throw new MyException( "exception.error");
        }
        TableDataInfo<BaseEntity> list = (TableDataInfo)proceed;

        for (BaseEntity data : list.getRows()) {
            if(ObjectUtil.isNotNull(data.getCreateUser())) {
                SysUserDept createUser = userCache.get(data.getCreateUser());

                data.setCreateUser(createUser != null ? createUser.getRealName() : null);
            }
            if(ObjectUtil.isNotNull(data.getUpdateUser())) {
                SysUserDept updateUser = userCache.get(data.getUpdateUser());
                data.setUpdateUser(updateUser != null ? updateUser.getRealName() : null);
            }
        }
        return proceed;
    }
}
